package com.mayn.web.dsr;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dtgrid.model.Pager;
import com.dtgrid.patch.DateJsonValueProcessor;
import com.dtgrid.utils.ExportUtils;
import com.dtgrid.utils.PagerPropertyUtils;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.POST;
import com.mayn.action.TaobaoCookieAction;
import com.mayn.jst.login.TaobaoLoginAction;
import com.mayn.jst.taobao.TaobaoDsrAction;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

public class DsrController extends Controller {

	private static final Logger LOG = LoggerFactory.getLogger(DsrController.class);

	public void index() {
		render("index.html");
	}

	public void getNewDsrData() {

		Boolean success = false;
		String code = "";
		String msg = "";
		String data = "";

		success = TaobaoDsrAction.getAllShopDsrData();
		if (success) {
			code = "1";
			msg = "采集成功";
		} else {
			code = "2";
			msg = "采集保存错误";
		}
		LOG.info(msg);
		renderJson(setJsonResponse(success, code, msg, data));
	}

	public void getNewDsrCookie() {
		String cookie = "";

		Boolean success = false;
		String code = "";
		String msg = "";
		String data = "";

		cookie = TaobaoCookieAction.getNewCookie();
		if (cookie != null && !cookie.equals("")) {
			success = true;
			code = "1";
			data = cookie;
			msg = "cookie获取成功";
		} else {
			success = false;
			code = "2";
			msg = "cookie不存在";
		}
		renderJson(setJsonResponse(success, code, msg, data));
	}

	public void saveDsrCookie() {
		String cookie = getPara("cookie");

		Boolean success = false;
		String code = "";
		String msg = "";
		String data = "";
		if (cookie != null && !cookie.trim().equals("")) {

			Boolean check = TaobaoLoginAction.checkDsrCookie(cookie);
			if (check) {
				success = TaobaoCookieAction.saveCookie(cookie);
				if (success) {
					code = "1";
					msg = "cookie保存成功";
				} else {
					code = "2";
					msg = "cookie保存错误";
				}
				LOG.info(msg);

			} else {
				code = "3";
				msg = "cookie校验失败，无法保存";
			}
		} else {
			success = false;
			code = "0";
			msg = "cookie参数传递错误!";
			LOG.error(msg);
		}
		renderJson(setJsonResponse(success, code, msg, data));
	}

	public void checkDsrCookie() {
		String cookie = getPara("cookie");

		Boolean success = false;
		String code = "";
		String msg = "";
		String data = "";
		if (cookie != null && !cookie.trim().equals("")) {
			success = TaobaoLoginAction.checkDsrCookie(cookie);
			if (success) {
				code = "1";
				msg = "cookie校验成功";
			} else {
				code = "2";
				msg = "cookie校验错误";
			}
			LOG.info(msg);
			renderJson(setJsonResponse(success, code, msg, data));
		} else {
			success = false;
			code = "0";
			msg = "cookie参数传递错误!";
			LOG.error(msg);
			renderJson(setJsonResponse(success, code, msg, data));
		}
	}

	@Before(POST.class)
	public void getNewDsrDataJson() throws IOException {
		Pager pager = new Pager();
		try {
			pager = PagerPropertyUtils.copy(JSONObject.fromObject(getPara("dtGridPager")));
			Map<String, Object> parameters = pager.getParameters();
			String statis_date = (String) parameters.get("statis_date");

			// 映射为int型
			int pageSize = pager.getPageSize();
			@SuppressWarnings({ "unused" })
			int startRecord = pager.getStartRecord();
			int recordCount = pager.getRecordCount();
			int nowPage = pager.getNowPage();
			int pageCount = pager.getPageCount();

			// 处理导出
			if (pager.getIsExport()) {
				// 如果是全部导出数据
				if (pager.getExportAllData()) {
					// 查询结果集放到信息中
					JSONObject dataObject = TaobaoDsrAction.getDsrJsonObjectFromDb(statis_date, pageSize, nowPage, true);
					net.sf.json.JSONArray ja = dataObject.getJSONArray("data");
					pager.setExportDatasFromJsonArray(ja);
				}
				ExportUtils.export(getRequest(), getResponse(), pager);
				renderNull();
				return;
			}

			JSONObject dataObject = TaobaoDsrAction.getDsrJsonObjectFromDb(statis_date, pageSize, nowPage, false);

			net.sf.json.JSONArray ja = dataObject.getJSONArray("data");
			recordCount = Integer.parseInt(dataObject.getString("total_count"));

			pager.setRecordCount(recordCount);
			pageCount = recordCount / pageSize + (recordCount % pageSize > 0 ? 1 : 0);
			pager.setPageCount(pageCount);
			// 查询结果集放到信息中

			pager.setExhibitDatasFromJsonArray(ja);
			// 设置查询成功
			pager.setIsSuccess(true);

		} catch (Exception e) {
			LOG.error(e.getMessage());
			// 设置查询失败
			pager.setIsSuccess(false);
		}
		// json-lib 日期补丁
		JsonValueProcessor jsonProcessor = new DateJsonValueProcessor();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.sql.Date.class, jsonProcessor);
		// 转换为JSON数据格式
		JSONObject pagerJSON = JSONObject.fromObject(pager, jsonConfig);

		// renderJson(ja);//此写法无法实现，待验证

		HttpServletResponse response = getResponse();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write(pagerJSON.toString());

		renderNull();
	}

	public static JSONObject setJsonResponse(Boolean success, String code, String msg, String data) {
		JSONObject ret = new JSONObject();
		ret.put("Success", success);
		ret.put("Code", code);
		ret.put("Msg", msg);
		ret.put("Data", data);
		return ret;
	}

}
